package com.example.emb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.emb.entity.*;
import com.example.emb.entity.pjo.WorkGroup;
import com.example.emb.mapper.*;
import com.example.emb.service.WorkService;
import com.example.emb.service.common.MinioService;
import com.example.emb.service.exception.WritingErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class WorkServiceImpl implements WorkService {
    @Autowired
    WorktableMapper worktableMapper;
    @Autowired
    StuworktableMapper stuworktableMapper;
    @Autowired
    UsrtableMapper usrtableMapper;
    @Autowired
    GroupdtableMapper groupdtableMapper;
    @Autowired
    GrouptableMapper grouptableMapper;
    @Autowired
    ShowworktableMapper showworktableMapper;
    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    MinioService minioService;
    @Autowired
    ClassdStutableMapper classdStuMapper;


    @Override
    public String TeacherInitWork(Worktable worktable) {
        Resource resource=resourceLoader.getResource("/homeWork/BaseMode.md");
        try (Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)) {
            //同时在这一步将一些基本信息给写进去
            String text=FileCopyUtils.copyToString(reader);
            worktableMapper.insert(worktable.setModel(text));
            return text;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public void changeBaseMode(String mode1) {
        //如果修改失败导致baseModel失效的话，就使用recover的版本写回去
        try (FileWriter writer = new FileWriter("/homeWork/BaseMode.md", StandardCharsets.UTF_8)) {
            writer.write(mode1);
        } catch (IOException e) {
            //如果修改失败导致baseModel失效的话，就使用recover的版本写回去
            Resource resource=resourceLoader.getResource("/homeWork/BaseModeRec.md");
            try (Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)) {
                //同时在这一步将一些基本信息给写进去
                String text=FileCopyUtils.copyToString(reader);
                FileWriter writer = new FileWriter("/homeWork/BaseMode.md", StandardCharsets.UTF_8);
                writer.write(text);
            } catch (IOException e1) {
                throw new WritingErrorException("写入失败已经回滚至原始模板");
            }
            e.printStackTrace();
        }
    }

    @Override
    public void deleteWork(int workId) throws Exception {
        //先删除有上交的学生的作业
        QueryWrapper<Stuworktable> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("workid",workId);
        List<Stuworktable> stuList=stuworktableMapper.selectList(queryWrapper);
        //因为有上传视频和zip，不能一次性删除完
        stuList.forEach(item->{
            //先删除video&zip
            String video=item.getVideo();
            String zip=item.getZip();
            try {
                minioService.deleteFile(video);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                minioService.deleteFile(zip);
            } catch (Exception e) {
                e.printStackTrace();
            }
            stuworktableMapper.deleteById(item.getId());
        });
        Worktable worktable=worktableMapper.selectById(workId);
//        minioService.deleteFile(worktable.getDetailurl());
        worktableMapper.deleteById(workId);
        return;
    }

    @Override
    public List<WorkGroup> selectHandedWork(int workId) {
        List<WorkGroup> list=new ArrayList<>();
        Worktable worktable=worktableMapper.selectById(workId);
        Double RepeatRate=worktable.getRepeatRate();
        QueryWrapper<Stuworktable> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("workid",workId);
        List<Stuworktable> stuList=stuworktableMapper.selectList(queryWrapper);

        //时间判断
        Date DDL=new Date(worktable.getEndTime().getTime());
        Date date=new Date();
        Boolean flag =DDL.getTime() > date.getTime() ? false :true;
        for(Stuworktable item:stuList){
            WorkGroup workGroup=new WorkGroup();
            QueryWrapper<Groupdtable> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("GroupId",item.getGroupId());
            List<Groupdtable> usrList=groupdtableMapper.selectList(queryWrapper1);
            String members="";
            for(Groupdtable usrG:usrList){
                members=members+","+usrG.getName();
            }
            workGroup.setMembers(members)
                    .setGroupId(item.getGroupId())
                    .setStuWorkId(item.getWorkid());

            //在这里分情况处理，已经截至了的和未截至的
            if(!flag){
                workGroup.setFinishTime(item.getFinishTime())
                        .setCheckResult(item.getRepeatRate())
                        .setIsAchieve(RepeatRate>item.getRepeatRate() ? true:false);
            }
            list.add(workGroup);
        }
        return list;
    }

    //这里查询的是上交都没有上交的小组
    //没有init过所以只能通过Group检索
    @Override
    public List<WorkGroup> selectUnHandedWork(int workId) {
//        List<Integer> UnHandedGroupList=new ArrayList<>();
        List<WorkGroup> list=new ArrayList<>();
        Worktable worktable=worktableMapper.selectById(workId);
        QueryWrapper<Grouptable> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("classId",worktable.getClassid());
        List<Grouptable> list1=grouptableMapper.selectList(queryWrapper);
        List<WorkGroup> handledGroup=selectHandedWork(workId);

        for (Grouptable grouptable : list1) {
            for (WorkGroup workGroup : handledGroup) {
                if(workGroup.getGroupId()==grouptable.getId()){
                    handledGroup.remove(workGroup);
                    list1.remove(grouptable);
                }
            }
        }
        //如果还有的情况的话
        if(list1.size()!=0){
            for (Grouptable grouptable : list1) {
                WorkGroup workGroup=new WorkGroup();
                QueryWrapper<Groupdtable> queryWrapper1=new QueryWrapper<>();
                queryWrapper1.eq("GroupId",grouptable.getId());
                List<Groupdtable> usrList=groupdtableMapper.selectList(queryWrapper1);
                String members="";
                for(Groupdtable usrG:usrList){
                    members=members+","+usrG.getName();
                }
                workGroup.setGroupId(grouptable.getId())
                        .setMembers(members);
            }
            return list;
        }
        else
            return null;
    }

    @Override
    public Stuworktable getStuWorkDetail(int stuWorkId) {
        Stuworktable stuworktable=stuworktableMapper.selectById(stuWorkId);
        return stuworktable;
    }

    @Override
    public void giveScore(Double score, int StuworkId) {
        UpdateWrapper<Stuworktable>updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("id",StuworkId)
                .set("mark",score);
        stuworktableMapper.update(null,updateWrapper);
        return;
    }

    //todo
    @Override
    public void isShowWork(int workId,String photo,String workName) {
        Showworktable showworktable=new Showworktable();
        Stuworktable stuworktable=stuworktableMapper.selectById(workId);
        int GroupId=stuworktable.getGroupId();
        QueryWrapper<Classdstutable> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("groupId",GroupId);
        List<Classdstutable> list=classdStuMapper.selectList(queryWrapper);
        Date date=new Date();
        java.sql.Date sqlDate=new java.sql.Date(date.getTime());
        String names="";
        for (Classdstutable classdStutable : list) {
            names+=classdStutable.getStuName();
        }

        showworktable
                .setWorkDoc(stuworktable.getWorkDoc())
                .setWorkName(workName)
                .setWorkId(workId)
                .setGroupId(GroupId)
                .setStuName(names)
                .setVideo(stuworktable.getVideo())
                .setModifiedTime(sqlDate);

        showworktableMapper.insert(showworktable);

    }



//    @Override
//    public List<Worktable> getAllWorks(Long uuid, int workId) {
//
//        return null;
//    }

    //更新作业的操作，主要是作业模板，查重率这些问题上的。在前端做出一定量的区分
    @Override
    public void updateWork(Worktable worktable) {
        worktableMapper.updateById(worktable);
        return;
    }

    //作业中提交的报告是同一份的
    @Override
    public int InitWork(int workId,int groupId) {
        if(isFinished(workId))
            return 0;
        Stuworktable stuworktable=new Stuworktable();
        Date date=new Date();
        java.sql.Date sqlDate=new java.sql.Date(date.getTime());
        stuworktable.setWorkid(workId)
                .setGroupId(groupId);
        int id=stuworktableMapper.insert(stuworktable);
        return id;
    }

    @Override
    public void updateWork(int stuWorkId, String WorkDoc,int WorkId) {
        if(isFinished(WorkId))
            return ;
        Stuworktable stuworktable=stuworktableMapper.selectById(stuWorkId);
        stuworktable.setWorkDoc(WorkDoc);
        stuworktableMapper.updateById(stuworktable);
        return;
    }

    @Override
    public String getWorkFile(int stuWorkId) {
        Stuworktable stuworktable=stuworktableMapper.selectById(stuWorkId);
        return stuworktable.getWorkDoc();
    }

//    @Override
//    public void InitShowWork(int stuWorkId,String WorkName,String photoUrl) {
//        Showworktable showworktable=new Showworktable();
//        Stuworktable stuworktable=stuworktableMapper.selectById(stuWorkId);
//        //查小组表，然后再获得组员名称
//        QueryWrapper<Groupdtable> queryWrapper=new QueryWrapper<>();
//        queryWrapper.eq("GroupId",stuworktable.getGroupId());
//        List<Groupdtable>  groupdtableList=groupdtableMapper.selectList(queryWrapper);
//        while (stuworktable!=null){
//            String name="";
//            for(Groupdtable g:groupdtableList){
//                name=name+" ,"+g.getName();
//            }
//            showworktable.setWorkDoc(stuworktable.getWorkDoc())
//                    .setVideo(stuworktable.getVideo())
//                    .setClassName(groupdtableList.get(0).getClassName())
//                    .setClassId(groupdtableList.get(0).getClassId())
//                    .setStuName(name)
//                    .setSource(photoUrl)
//                    .setWorkId(stuworktable.getWorkid());
//            if(WorkName!=null)
//                showworktable.setWorkName(WorkName);
//            else {
//                int workId=stuworktable.getWorkid();
//                Worktable worktable=worktableMapper.selectById(workId);
//                showworktable.setWorkName(worktable.getName());
//            }
//            showworktableMapper.insert(showworktable);
//            return;
//        }
//        return;
//    }

    @Override
    public void updatePhoto(int showWorkId, String photoUrl) {
        Showworktable showworktable=showworktableMapper.selectById(showWorkId);
        showworktableMapper.updateById(showworktable);
        return;
    }

    private boolean isFinished(int WorkId){
        QueryWrapper<Worktable>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id", WorkId);
        Worktable worktable=worktableMapper.selectOne(queryWrapper);
        Date date=new Date();
        java.sql.Date sqlDate=new java.sql.Date(date.getTime());
        //超时了
        if(sqlDate.getTime()>worktable.getEndTime().getTime())
            return false;
        else
            return true;
    }
}
